// 
//  Copyright © 2009 Jiří Zárevúcky <zarevucky.jiri@gmail.com>
// 
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Affero General Public License as
//  published by the Free Software Foundation, either version 3 of the
//  License, or (at your option) any later version.
// 
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU Affero General Public License for more details.
// 
//  You should have received a copy of the GNU Affero General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
// 
// 

using System;
using System.Collections.Generic;

using Anculus.Core;

using Galaxium.Protocol.Xmpp.Library.Xml;
using Galaxium.Protocol.Xmpp.Library.Extensions.Disco;

namespace Galaxium.Protocol.Xmpp.Library
{
	public static class CapsHelper
	{
		private static Dictionary<string, Info> _cache;
		
		static CapsHelper ()
		{
			_cache = new Dictionary<string, Info> ();
		}
		
		public static void Retrieve (Client client, JabberID jid,
		                             Element caps, Action<Info> callback)
		{
			var url = caps ["node"];
			var ver = caps ["ver"];
			
			Info info;
			if (_cache.TryGetValue (caps ["ver"], out info)) {
				callback (info);
				Log.Debug ("Verification string " + ver + " found in cache.");
				return;
			}
			
			// FIXME: don't make multiple request for the same verification string,
			//        queue jid's and callbacks instead
			
			var info_request = new InfoRequest (client, jid, url + '#' + ver);
			info_request.ReceivedEvent += (s, e) => {
				info = (s as InfoRequest).Result;
				Verify (info, ver);
				callback (info);
			};
			info_request.Request ();
		}
		
		private static void Verify (Info info, string ver)
		{
			if (info.GenerateVerificationString () == ver) {
				Log.Debug ("Capabilities verified, adding to the cache.");
				_cache [ver] = info;
			}
			
			// TODO: persistent cache
		}
	}
}
